﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WorkStation.Frameworks.EasyBus
{
    #region 接口
    
    /// <summary>
    /// 监听服务器对象
    /// </summary>
    public interface IServer
    {
        /// <summary>
        /// 监听器集合
        /// </summary>
        Dictionary<string, IMessageListener> Listeners { get; set; }

        /// <summary>
        /// 注册监听器（将会自动添加该监听器的错误消息监听器）
        /// </summary>
        /// <param name="listener"></param>
        /// <returns></returns>
        IServer RegisterListener(IMessageListener listener);

        /// <summary>
        /// 启动
        /// </summary>
        void Start();

        /// <summary>
        /// 停止
        /// </summary>
        void Stop();
    }

    #endregion

    /// <summary>
    /// 默认监听服务器对象
    /// </summary>
    public class DefaultServer : IServer
    {
        public Dictionary<string, IMessageListener> Listeners { get; set; }

        public DefaultServer()
        {
            this.Listeners = new Dictionary<string, IMessageListener>();
        }

        public void Start()
        {
            foreach (KeyValuePair<string, IMessageListener> pair in this.Listeners)
            {
                pair.Value.BeginListen();
            }
        }

        public void Stop()
        {
            foreach (KeyValuePair<string, IMessageListener> pair in this.Listeners)
            {
                pair.Value.StopListen();
            }
        }

        public IServer RegisterListener(IMessageListener listener)
        {
            if (listener == null)
            {
                throw new ArgumentNullException("listener");
            }

            this.Listeners.Add(listener.Name, listener);

            return this;
        }
    }
}
